"""
Redis缓存服务模块
用于处理基本Redis缓存功能
支持Redis服务器和内存模拟两种模式
"""
import redis
import json
from datetime import datetime
from config import settings

class RedisService:
    """Redis缓存服务 - 支持流式输出存储逻辑"""
    
    def __init__(self):
        """初始化Redis服务"""
        self.use_redis = True
        try:
            # 尝试连接Redis服务器
            self.client = redis.from_url(settings.redis_url)
            if settings.redis_password:
                self.client = redis.from_url(
                    settings.redis_url, 
                    password=settings.redis_password
                )
            # 测试连接
            self.client.ping()
            print("Redis服务连接成功")
        except Exception as e:
            print(f"Redis服务连接失败，使用内存缓存: {e}")
            self.use_redis = False
            # 简化的内存缓存实现
            class SimpleMemoryCache:
                def __init__(self):
                    self.data = {}
                
                def setex(self, key, expire, value):
                    self.data[key] = value
                
                def get(self, key):
                    return self.data.get(key)
                
                def delete(self, key):
                    if key in self.data:
                        del self.data[key]
                
                def exists(self, key):
                    return key in self.data
                
                def hset(self, key, field, value):
                    if key not in self.data:
                        self.data[key] = {}
                    self.data[key][field] = value
                
                def hget(self, key, field):
                    if key in self.data and field in self.data[key]:
                        return self.data[key][field]
                    return None
                
                def hgetall(self, key):
                    return self.data.get(key, {})
                
                def hdel(self, key, field):
                    if key in self.data and field in self.data[key]:
                        del self.data[key][field]
            
            self.client = SimpleMemoryCache()
    
    def store_streaming_message(self, session_id: str, message_id: str, content: str, is_final: bool = False):
        """存储流式消息数据到Redis"""
        try:
            # 创建流式消息数据结构
            stream_data = {
                'session_id': session_id,
                'message_id': message_id,
                'content': content,
                'is_final': is_final,
                'updated_at': datetime.now().isoformat()
            }
            
            # 存储到Redis，设置过期时间（10分钟）
            key = f"streaming_message:{session_id}:{message_id}"
            self.client.setex(key, 600, json.dumps(stream_data))
            
            # 同时存储会话的流式状态
            status_key = f"streaming_session:{session_id}"
            self.client.hset(status_key, message_id, json.dumps({
                'is_active': True,
                'is_final': is_final,
                'last_updated': datetime.now().isoformat()
            }))
            # 设置会话状态过期时间为10分钟
            self.client.expire(status_key, 600)
            
            return True
        except Exception as e:
            print(f"存储流式消息失败: {e}")
            return False
    
    def get_streaming_message(self, session_id: str, message_id: str):
        """从Redis获取流式消息数据"""
        try:
            key = f"streaming_message:{session_id}:{message_id}"
            data = self.client.get(key)
            if data:
                # 处理字节字符串数据：如果是字节字符串，解码为字符串
                if isinstance(data, bytes):
                    data = data.decode('utf-8')
                return json.loads(data)
            return None
        except Exception as e:
            print(f"获取流式消息失败: {e}")
            return None
    
    def delete_streaming_message(self, session_id: str, message_id: str):
        """删除流式消息数据"""
        try:
            # 删除消息数据
            key = f"streaming_message:{session_id}:{message_id}"
            self.client.delete(key)
            
            # 删除会话状态
            status_key = f"streaming_session:{session_id}"
            self.client.hdel(status_key, message_id)
            
            # 如果会话没有其他流式消息，删除会话状态
            remaining = self.client.hgetall(status_key)
            if not remaining:
                self.client.delete(status_key)
            
            return True
        except Exception as e:
            print(f"删除流式消息失败: {e}")
            return False
    
    def get_session_streaming_status(self, session_id: str):
        """获取会话的流式状态"""
        try:
            status_key = f"streaming_session:{session_id}"
            status_data = self.client.hgetall(status_key)
            
            if not status_data:
                return {'has_active_streaming': False, 'active_messages': []}
            
            active_messages = []
            for message_id, status_json in status_data.items():
                try:
                    # 处理字节字符串键：如果是字节字符串，解码为字符串
                    if isinstance(message_id, bytes):
                        message_id = message_id.decode('utf-8')
                    
                    # 处理字节字符串值：如果是字节字符串，解码为字符串
                    if isinstance(status_json, bytes):
                        status_json = status_json.decode('utf-8')
                    
                    status = json.loads(status_json)
                    if status.get('is_active', False) and not status.get('is_final', False):
                        active_messages.append({
                            'message_id': message_id,
                            'last_updated': status.get('last_updated')
                        })
                except Exception as e:
                    print(f"处理流式状态数据失败 - 消息ID: {message_id}, 错误: {e}")
                    continue
            
            return {
                'has_active_streaming': len(active_messages) > 0,
                'active_messages': active_messages
            }
        except Exception as e:
            print(f"获取会话流式状态失败: {e}")
            return {'has_active_streaming': False, 'active_messages': []}
    
    def get_all_streaming_messages_for_session(self, session_id: str):
        """获取会话的所有流式消息"""
        try:
            status_key = f"streaming_session:{session_id}"
            status_data = self.client.hgetall(status_key)
            
            messages = []
            for message_id, _ in status_data.items():
                # 处理字节字符串键：如果是字节字符串，解码为字符串
                if isinstance(message_id, bytes):
                    message_id = message_id.decode('utf-8')
                
                message_data = self.get_streaming_message(session_id, message_id)
                if message_data:
                    messages.append(message_data)
            
            return messages
        except Exception as e:
            print(f"获取会话流式消息失败: {e}")
            return []


# 全局Redis服务实例
redis_service = RedisService()